package cn.tedu.fengyuback.user.service.impl;

import cn.tedu.fengyuback.base.exception.ServiceException;
import cn.tedu.fengyuback.base.response.StatusCode;
import cn.tedu.fengyuback.user.mapper.UserMapper;
import cn.tedu.fengyuback.user.pojo.dto.UserLoginParam;
import cn.tedu.fengyuback.user.pojo.dto.UserSaveParam;
import cn.tedu.fengyuback.user.pojo.entity.User;
import cn.tedu.fengyuback.user.pojo.vo.UserVO;
import cn.tedu.fengyuback.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("用户登录，参数：{}",userLoginParam);
        UserVO userVO = userMapper.selectByUsername(userLoginParam.getUsername());
        if(userVO==null){
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if(!userVO.getPassword().equals(userLoginParam.getPassword())){
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        return userVO;
    }
    @Override
    public void saveUser(UserSaveParam userSaveParam) {
        User user = new User();
        BeanUtils.copyProperties(userSaveParam,user);
        if(user.getId()==null){
            //新增用户时要判断该用户名是否存在
            if(userMapper.selectByUsername(user.getUsername())!=null){
                throw new ServiceException(StatusCode.USERNAME_ALREADY_EXISTS);
            }
            user.setPassword(userSaveParam.getPassword());
            user.setNickname(userSaveParam.getNickname());
            user.setCreateTime(new Date());
            userMapper.insert(user);
        }else{
            user.setUpdateTime(new Date());
            userMapper.update(user);
        }
    }
}